package com.ztx.controller;

import com.ztx.pojo.User;
import com.ztx.service.UserService;
import com.ztx.utils.CommonResult;
import com.ztx.pojo.dto.UserDto;
import com.ztx.utils.JwtTokenUtil;
import com.ztx.utils.TokenResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RequestMapping("/user")
@RestController
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    JwtTokenUtil jwtTokenUtil;

    @Autowired
    HttpServletRequest request;

    @PostMapping("/login")
    public CommonResult<TokenResponse> login(@RequestBody User user) {

        String username = user.getUsername();
        String password = user.getPassword();

        User user_login = userService.login(username, password);

        if (user_login == null) {
            return CommonResult.error(400, "用户名密码错误~");
        } else {
            // 生成访问令牌和刷新令牌
            Long userId = user_login.getUserId();
            String accessToken = jwtTokenUtil.generateAccessToken(userId);
            String refreshToken = jwtTokenUtil.generateRefreshToken(userId);
            TokenResponse token_resp = new TokenResponse(accessToken, refreshToken);
            return CommonResult.success(token_resp);
        }
    }

    @GetMapping("/getInfo")
    public CommonResult<User> getInfo() {
        String token = request.getHeader("Authorization").substring(7);

        Long userId = jwtTokenUtil.getUserIdFromToken(token);
        User user = userService.getInfo(userId);

        if (user == null) {
            return CommonResult.error(400, "找不到该用户~");
        } else {
            return CommonResult.success(user);
        }
    }

    @PostMapping("addUser")
    public CommonResult<?> addUser(@RequestBody UserDto userDto) {

        userService.saveWithRoles(userDto);

        return CommonResult.success("success");
    }

    @GetMapping("list")
    public CommonResult<List<UserDto>> getUserList() {

        List<UserDto> userDtos = userService.listUserDto();

        return CommonResult.success(userDtos);
    }

    @DeleteMapping("/{id}")
    public CommonResult<?> deleteById(@PathVariable Long id) {

        userService.deleteWithRoles(id);

        return CommonResult.success("success");
    }

    @GetMapping("/{userId}")
    public CommonResult<UserDto> getById(@PathVariable Long userId) {

        UserDto userDto = userService.getByIdWithRoles(userId);

        return CommonResult.success(userDto);
    }

    @PutMapping("updateUser")
    public CommonResult<?> updateUser(@RequestBody UserDto userDto) {

        userService.updateWithRoles(userDto);

        return CommonResult.success("success");
    }

}
